package com.zw.pdm.module.craft.service;

import com.zw.pdm.entity.com.DsnTaskCommon;
import com.zw.pdm.entity.craft.*;
import com.zw.pdm.entity.designtask.DsnGant;
import com.zw.pdm.entity.designtask.DsnProStruct;
import com.zw.pdm.entity.est.Card;
import com.zw.pdm.entity.rep.Result;
import com.zw.pdm.entity.rep.Sheet;
import com.zw.pdm.entity.sys.Role;
import com.zw.pdm.module.craft.mapper.CraftMaintainMapper;
import com.zw.pdm.module.craft.mapper.CraftProQueryMapper;
import com.zw.pdm.module.craft.mapper.CraftReceiveMapper;
import com.zw.pdm.module.craft.model.CraGantBillModel;
import com.zw.pdm.module.craft.model.CraProQueryModel;
import com.zw.pdm.module.craft.model.CraQueryModel;
import com.zw.pdm.module.craft.model.TaskStatusModel;
import com.zw.pdm.module.craft.repository.CraftCraGantRepository;
import com.zw.pdm.module.craft.repository.CraftMakeDetailRepository;
import com.zw.pdm.module.craft.repository.CraftTaskDetaiRepository;
import com.zw.pdm.module.designtask.model.DsnGantBillModel;
import com.zw.pdm.module.designtask.repository.DsnTaskCommonRepository;
import com.zw.pdm.module.report.mapper.ChangeMapper;
import com.zw.pdm.module.report.mapper.PlanMapper;
import com.zw.pdm.module.report.mapper.SheetMapper;
import com.zw.pdm.module.report.model.Project;
import com.zw.pdm.module.system.service.LogService;
import com.zw.pdm.util.ShiroUtils;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.persistence.Id;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.zw.pdm.util.BeanUtil.copy;


/**
 * @Description:
 * @Author: China.sgl
 * @Date: 2019/12/6 08:42
 */
@Service
@SuppressWarnings("all")
public class CraftProQueryService {

    @Autowired
    private PlanMapper planMapper;
    @Autowired
    private CraftMakeDetailRepository craftMakeDetailRepository;
    @Autowired
    private CraftReceiveMapper craftReceiveMapper;
    @Autowired
    private ChangeMapper changeMapper;
    @Autowired
    private CraftProQueryMapper craftProQueryMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private DsnTaskCommonRepository dsnTaskCommonRepository;
    @Autowired
    private CraftTaskDetaiRepository craftTaskDetaiRepository;
    @Autowired
    private CraftCraGantRepository craftCraGantRepository;
    @Autowired
    private SheetMapper sheetMapper;
    @Value("${saleUrl}")
    private String saleUrl;
    /**
     * 接收列表查询cra_make_sheet
     */
    public List<CraProQueryModel> selectPro(CraProQueryModel craProQueryModel) {
        return craftProQueryMapper.selectPro(craProQueryModel);
    }

    /**
     * 通过ID查询项目信息
     *
     * @param proId
     * @return
     */
    public CraProQueryModel selectProqueryById(Integer proId) {
        return craftProQueryMapper.selectProqueryById(proId);
    }

    /**
     * 通过项目ID查询工艺主表
     * @param proId
     * @return
     */
    public List<CraMakeSheet> selectCraMakeSheetByProId(Integer proId) {
        return craftProQueryMapper.selectCraMakeSheetByProId(proId);
    }

    /**
     * 通过项目ID 和 专业 查询工艺主表
     * @param proId
     * @param specialId
     * @return
     */
    public  List<CraMakeSheet> selectCraMakeSheetByProIdAndspecialId(Integer proId,Integer specialId){
        CraMakeSheet craMakeSheet = new CraMakeSheet();
        craMakeSheet.setProId(proId);
        craMakeSheet.setSpecialId(specialId);
        return craftProQueryMapper.selectCraMakeSheetByProIdAndspecialId(craMakeSheet);
    }

    /**
     * 根据工艺主表ID查询工艺卡表
     * @param sheetId
     * @return
     */
    public  List<Card> selectCraCardSheetBysheetId(Integer sheetId){
        return  craftProQueryMapper.selectCraCardSheetBysheetId(sheetId);
    }
    /**
     * 根据工艺主表ID查询提报计划
     * @param sheetId
     * @return
     */
    public  List<Sheet> selectRepResultBysheetId(Sheet sheet){
        return  craftProQueryMapper.selectRepResultBysheetId(sheet);
    }

    /**
     * 修改任务完成状态
     * @param deptId
     * @param statusSj
     * @param statusSC
     * @param code
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public  boolean updateTastCommonStatus(Integer deptId,Integer statusSj, Integer statusSC,String code){
        DsnTaskCommon dsnTaskCommon = new DsnTaskCommon();
        dsnTaskCommon.setProCode(code);
        dsnTaskCommon.setDeptId(deptId);
        dsnTaskCommon.setStatus(statusSj);
        dsnTaskCommon.setComTaskNameId(1);
        DsnTaskCommon dsnTaskCommon1 = new DsnTaskCommon();
        dsnTaskCommon1.setProCode(code);
        dsnTaskCommon1.setDeptId(deptId);
        dsnTaskCommon1.setStatus(statusSC);
        dsnTaskCommon1.setComTaskNameId(4);
        craftProQueryMapper.updateTastCommonStatus(dsnTaskCommon);
        craftProQueryMapper.updateTastCommonStatus(dsnTaskCommon1);
        logService.saveLog("设计任务和成本信息输出完成状态修改", "修改项目编号：" +code);
        return  true;
    }

    /**
     * 根据项目编号，部分，专业查询 工艺主单
     * @param craMakeSheet
     * @return
     */
    public List<CraMakeSheet> selectCraCardSheetByD(CraMakeSheet craMakeSheet) {
        return  craftProQueryMapper.selectCraCardSheetByD(craMakeSheet);
    }
    /**
     * 根据条件查询部分
     *
     * @param proId
     * @return
     */
    public List<DsnProStruct> findProStructByProId(Integer proId) {

        return craftProQueryMapper.findProStructByProId(proId);
    }

    /**
     * 提报计划输出表
     * @param result
     * @return
     */
    public List<Result> findResultByQuery(Result result) {
        return  craftProQueryMapper.findResultByQuery(result);
    }

    /**
     * 接收列表改
     * @param craTaskDetail
     * @return
     */
    public List<CraQueryModel> selectProDetail(CraQueryModel craQueryModel) {
        return  craftProQueryMapper.selectProDetail(craQueryModel);
    }

    public List<CraQueryModel> selectProDetailByPart(CraQueryModel craQueryModel) {
        return  craftProQueryMapper.selectProDetailByPart(craQueryModel);
    }

    /**
     * 获取 查看页面数据
     * @param proId
     * @return
     */

    public List<CraTaskDetail> selectTaskStatusModel(Integer proId) {
        return craftProQueryMapper.selectCraTaskDetailByProId(proId);

//        List<TaskStatusModel> taskStatusModelList = new ArrayList<TaskStatusModel>();
//        List<CraQueryModel> craQueryModelList = selectProDetailByProId(proId);
//        int jixie = 0;
//        int jixie1 = 0;
//        int jixie2 = 0;
//        int jixie3 = 0;
//        int jixie4 = 0;
//        int jixie11 = 0;
//        int jixie22 = 0;
//        int jixie33 = 0;
//        int jixie44 = 0;
//        String specialJiXie = "";
//        int liuti = 0;
//        int liuti1 = 0;
//        int liuti2 = 0;
//        int liuti3 = 0;
//        int liuti4 = 0;
//        int liuti11 = 0;
//        int liuti22 = 0;
//        int liuti33 = 0;
//        int liuti44 = 0;
//        String specialLiuti = "";
//        for (int i = 0; i < craQueryModelList.size(); i++) {
//            if (craQueryModelList.get(i).getSpecialId()==60){
//                if (craQueryModelList.get(i).getCraftStatus()>2){
//                    jixie1++;
//                }else if(craQueryModelList.get(i).getCraftStatus()==2){
//                    jixie11=1;
//                }
//                if (craQueryModelList.get(i).getMaterialStatus()>2){
//                    jixie2++;
//                }else if(craQueryModelList.get(i).getMaterialStatus()==2){
//                    jixie22=1;
//                }
//                if (craQueryModelList.get(i).getOutsourcingStatus()>2){
//                    jixie3++;
//                }else if(craQueryModelList.get(i).getOutsourcingStatus()==2){
//                    jixie33=1;
//                }
//                jixie4=craQueryModelList.get(i).getCostStatus();
//
//                specialJiXie = craQueryModelList.get(i).getSpecial();
//                jixie++;
//            }else if(craQueryModelList.get(i).getSpecialId()==61){
//                if (craQueryModelList.get(i).getCraftStatus()>2){
//                    liuti1++;
//                }else if(craQueryModelList.get(i).getCraftStatus()==2){
//                    liuti11=1;
//                }
//                if (craQueryModelList.get(i).getMaterialStatus()>2){
//                    liuti2++;
//                }else if (craQueryModelList.get(i).getMaterialStatus()==2){
//                    liuti22=1;
//                }
//                if (craQueryModelList.get(i).getOutsourcingStatus()>2){
//                    liuti3++;
//                }else  if (craQueryModelList.get(i).getOutsourcingStatus()==2){
//                    liuti33=1;
//                }
//                liuti4=craQueryModelList.get(i).getCostStatus();
//                specialLiuti = craQueryModelList.get(i).getSpecial();
//                liuti++;
//            }
//        }
//        if (jixie>0){
//            TaskStatusModel taskStatusModel = new TaskStatusModel();
//            taskStatusModel.setProId(craQueryModelList.get(0).getProId());
//            taskStatusModel.setSpecial(specialJiXie);
//            taskStatusModel.setSpecialId(60);
//            taskStatusModel.setStatusOne(jixie11==1?2: jixie1==0?1:jixie1==jixie?3:2);
//            taskStatusModel.setStatusOne1(jixie1 +"/"+jixie);
//            taskStatusModel.setStatusTwo(jixie22==1?2:jixie2==0?1:jixie2==jixie?3:2);
//            taskStatusModel.setStatusTwo1(jixie2 +"/"+jixie);
//            taskStatusModel.setStatusThree(jixie33==1?2:jixie3==0?1:jixie3==jixie?3:2);
//            taskStatusModel.setStatusThree1(jixie3 +"/"+jixie);
//            taskStatusModel.setStatusFour(jixie4);
//            taskStatusModelList.add(taskStatusModel);
//        }
//        if (liuti>0){
//            TaskStatusModel taskStatusModel = new TaskStatusModel();
//            taskStatusModel.setProId(craQueryModelList.get(0).getProId());
//            taskStatusModel.setSpecial(specialLiuti);
//            taskStatusModel.setSpecialId(61);
//            taskStatusModel.setStatusOne(liuti11==1?2:liuti1==0?1:liuti1==liuti?3:2);
//            taskStatusModel.setStatusOne1(liuti1 +"/"+liuti);
//            taskStatusModel.setStatusTwo(liuti22==1?2:liuti2==0?1:liuti2==liuti?3:2);
//            taskStatusModel.setStatusTwo1(liuti2 +"/"+liuti);
//            taskStatusModel.setStatusThree(liuti33==1?2:liuti3==0?1:liuti3==liuti?3:2);
//            taskStatusModel.setStatusThree1(liuti3 +"/"+liuti);
//            taskStatusModel.setStatusFour(liuti4);
//            taskStatusModelList.add(taskStatusModel);
//        }
//        return  taskStatusModelList;
    }

    /**
     * 按项目id 查询 CraQueryModel对象
     * @param proId
     * @return
     */
    private List<CraQueryModel> selectProDetailByProId(Integer proId) {
        return  craftProQueryMapper.selectProDetailByProId(proId);
    }

    /**
     * 查询成本信息输出 明细 （根据项目号 和 任务名称Id 查询）
     * @param dsnTaskCommon
     * @return
     */
    public List<DsnTaskCommon> selectdsnTaskCommonByProIdAndComTaskNameId(DsnTaskCommon dsnTaskCommon) {
        return  craftProQueryMapper.selectdsnTaskCommonByProIdAndComTaskNameId(dsnTaskCommon);
    }

    /**
     * 更新成本信息输出 状态明细
     * @param dsnTaskCommon
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCostStatus(DsnTaskCommon dsnTaskCommon) {
        String name ="";
        DsnTaskCommon dsnTaskCommon1 = dsnTaskCommonRepository.getOne(dsnTaskCommon.getId());
        CraTaskDetail craTaskDetail = craftTaskDetaiRepository.getOne(dsnTaskCommon1.getCraTaskDetailId());
        dsnTaskCommon1.setStatus(dsnTaskCommon.getStatus());
        dsnTaskCommon1.setUpdateUser(ShiroUtils.getUser().getName());
        dsnTaskCommon1.setUpdateTime(new Date());
        dsnTaskCommon1.setEndTime(dsnTaskCommon.getEndTime());
        dsnTaskCommon1.setStartTime(dsnTaskCommon.getStartTime());
        dsnTaskCommon1.setRemark(dsnTaskCommon.getRemark());
        dsnTaskCommonRepository.save(dsnTaskCommon1);
        if (dsnTaskCommon1.getComTaskNameId()==1){
            name="工艺编制";
            craTaskDetail.setCraftStatus(dsnTaskCommon.getStatus());
            String a = saleUrl;
            boolean boolFig = updateCraftStatus(saleUrl + "/projectScheduling/updateCraftStatus", dsnTaskCommon1.getProCode(),dsnTaskCommon1.getStatus(),dsnTaskCommon1.getEndTime());
            if(!boolFig){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }else  if (dsnTaskCommon1.getComTaskNameId()==4){
            name="成本信息输出";
            craTaskDetail.setCostStatus(dsnTaskCommon.getStatus());
        }else if (dsnTaskCommon1.getComTaskNameId()==9){
            name="原材料计划";
            craTaskDetail.setMaterialStatus(dsnTaskCommon.getStatus());
        } else  if (dsnTaskCommon1.getComTaskNameId()==10){
            name="外协件计划";
            craTaskDetail.setOutsourcingStatus(dsnTaskCommon.getStatus());
        }
        craftTaskDetaiRepository.save(craTaskDetail);
//        dsnTaskCommon.setUpdateUser(ShiroUtils.getUser().getName());
//        dsnTaskCommon.setUpdateTime(new Date());
//        int a = craftProQueryMapper.updateCraTaskDetail(dsnTaskCommon);
//        int b = craftProQueryMapper.updateDsnTaskCommon(dsnTaskCommon);
        logService.saveLog(name+"状态维护", "项目Id-编号：" +dsnTaskCommon1.getProId()+"-"+dsnTaskCommon1.getProName());
        return true;
    }

    /**
     * 跨域修改 项目状态
     *
     * @param saleUrl   接口地址
     * @param proCode   项目编号
     * @param Status 项目状态
     * @return
     */
    private boolean updateCraftStatus(String saleUrl, String proCode, Integer Status,Date endTime) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> bodyMap = new LinkedMultiValueMap<>();
        bodyMap.add("proCode", proCode);
        bodyMap.add("Status", Status.toString());
        if (endTime !=null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            bodyMap.add("endTime",simpleDateFormat.format(endTime));
        }else{
            bodyMap.add("endTime",null);
        }
        return restTemplate.postForObject(saleUrl, bodyMap, Boolean.class);
    }

    /**
     * 更新除成本信息输出 状态明细
     * @param dsnTaskCommon
     * @return
     */
    public boolean editTaskStatus(DsnTaskCommon dsnTaskCommon) {
        DsnTaskCommon dsnTaskCommon1 = dsnTaskCommonRepository.getOne(dsnTaskCommon.getId());
        dsnTaskCommon1.setUpdateTime(new Date());
        dsnTaskCommon1.setUpdateUser(ShiroUtils.getUser().getName());
        dsnTaskCommon1.setRemark(dsnTaskCommon.getRemark());
        dsnTaskCommon1.setStartTime(dsnTaskCommon.getStartTime());
        dsnTaskCommon1.setEndTime(dsnTaskCommon.getEndTime());
        dsnTaskCommon1.setStatus(dsnTaskCommon.getStatus());
        dsnTaskCommonRepository.save(dsnTaskCommon1);
        int a =  craftProQueryMapper.editCraTaskDetail(dsnTaskCommon1);
        return  true;
    }

    public String selectCraMakeSheetSetionNameByProId(Integer proId) {
        String setionNames="";
        List<CraReleaseDetail> craReleaseDetailList =  craftProQueryMapper.selectCraMakeSheetSetionNameByProId(proId);
        if (craReleaseDetailList.size()>0){
            for (int i = 0; i < craReleaseDetailList.size(); i++) {
                if (i==craReleaseDetailList.size()-1){
                    setionNames+=craReleaseDetailList.get(i).getSectionName();
                }else {

                    setionNames+=craReleaseDetailList.get(i).getSectionName()+",";
                }
            }
        }else {
            setionNames="工艺一科";
        }
        return setionNames;
    }
    /**
     * 所长用户角色
     *
     * @param userId
     * @return
     */
    public List<Role> findUserRoleByUserId(Integer userId) {
        return  craftProQueryMapper.findUserRoleByUserId(userId);
    }
    /**
     * 根据项目编号和登入人员获取项目计划
     *
     * @param proCode
     * @param createCode
     * @return
     */
    public List<CraGant> findGantListByProCodeAndCreateCode(String proCode, String createCode) {

        return craftProQueryMapper.findGantListByProCodeAndCreateCode(proCode, createCode, ShiroUtils.getUser().getDeptId());
    }
    /**
     * 保存项目计划甘特图
     *
     * @param CraGantBillModel
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean save(CraGantBillModel craGantBillModel) {

        // 取得项目信息
        Project project = sheetMapper.findProjectByCode(craGantBillModel.getFormData().getProCode()).get(0);
        if (project == null || project.getId() == null) {
            return false;
        }

        // 新增
        List<CraGant> craGantAdds = craGantBillModel.getInsertData();
        if (craGantAdds != null) {
            CraGant craGantAdd;
            for (var i = 0; i < craGantAdds.size(); i++) {
                craGantAdd = new CraGant();
                copy(craGantAdds.get(i), craGantAdd);
                craGantAdd.setProId(project.getId());
                craGantAdd.setProCode(project.getCode());
                craGantAdd.setProName(project.getName());
                craGantAdd.setTaskerName(craGantAdd.getTaskerName().replace("\n", "").replace(" ", ""));
                craGantAdd.setDeptId(craGantBillModel.getFormData().getDeptId());
                craGantAdd.setDeptName(craGantBillModel.getFormData().getDeptName());
                craGantAdd.setTaskType("设计");
                craGantAdd.setCreateCode(ShiroUtils.getUser().getAccount());
                craGantAdd.setCreateName(ShiroUtils.getUser().getName());
                craftCraGantRepository.save(craGantAdd);
            }
        }

        // 修改
        List<CraGant> craGantUdps = craGantBillModel.getUpdateData();
        if (craGantUdps != null) {
            CraGant craGantUdp;
            for (var i = 0; i < craGantUdps.size(); i++) {
                craGantUdp = new CraGant();
                copy(craGantUdps.get(i), craGantUdp);
                // 判断行内容是否都为空，都为空的数据执行删除操作
                if(craGantUdp.getTaskerName().equals("") && craGantUdp.getContent().equals("") && craGantUdp.getStartTime() == null
                        && craGantUdp.getEndTime() == null && craGantUdp.getDiachronic() == null && craGantUdp.getRemark().equals("")){
                    // 执行删除操作
                    craftProQueryMapper.delCraGant(craGantUdp.getId());
                    continue;
                }
                craGantUdp.setProId(project.getId());
                craGantUdp.setProCode(project.getCode());
                craGantUdp.setProName(project.getName());
                craGantUdp.setTaskerName(craGantUdp.getTaskerName().replace("\n", "").replace(" ", ""));
                craGantUdp.setDeptId(craGantBillModel.getFormData().getDeptId());
                craGantUdp.setDeptName(craGantBillModel.getFormData().getDeptName());
                craGantUdp.setTaskType("工艺");
                craGantUdp.setCreateCode(ShiroUtils.getUser().getAccount());
                craGantUdp.setCreateName(ShiroUtils.getUser().getName());
                craftCraGantRepository.save(craGantUdp);
            }
        }

        // 删除
        List<Integer> dsnGantDels = craGantBillModel.getDelData();
        if (dsnGantDels != null) {
            for (var i = 0; i < dsnGantDels.size(); i++) {
                craftProQueryMapper.delCraGant(dsnGantDels.get(i));
            }
        }

        logService.saveLog("保存工艺项目计划甘特图", "项目编号：" + project.getCode() + "<br>项目名称：" + project.getName());
        return true;
    }
    /**
     * 根据条件查询分配任务
     *
     * @param dsnGant
     * @return
     */
    public List<CraGant> findDsnGantByQuery(CraGant craGant) {

        // 加载时无项目编号不显示列表数据
        if ((craGant.getProCode() == null || craGant.getProCode() == "")
                && (craGant.getProCodeQuery() == null || craGant.getProCodeQuery() == "")) {
            craGant.setProCode("无编号");
        }
        return craftProQueryMapper.findDsnGantByQuery(craGant);
    }
}
